package com.gl.order.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.order.entity.AreaDict;
import com.gl.order.entity.TMenu;
import com.gl.order.entity.TRoleMenu;
import com.gl.order.entity.dto.MenuAddDto;
import com.gl.order.entity.dto.MenuPageDto;
import com.gl.order.mapper.TMenuMapper;
import com.gl.order.mapper.TRoleMenuMapper;
import com.gl.order.service.TMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TMenuServiceImpl extends ServiceImpl<TMenuMapper, TMenu> implements TMenuService {

    @Autowired
    TRoleMenuMapper tRoleMenuMapper;

//    @Override
//    public List findByUserId(String userId) {
//        List<TMenu> menus = this.baseMapper.findByUserId(userId);
//        List<TMenu> finalTreeList = new ArrayList();
//        Iterator<TMenu> var11 = menus.iterator();
//        while(var11.hasNext()) {
//            TMenu node = var11.next();
//            if ("#".equals(node.getPid())) {
//                finalTreeList.add(node);
//                this.innerBuild(menus, node);
//            }
//        }
//        return finalTreeList;
//    }

    @Override
    public List findByRole(String roleId) {
        return null;
    }

//    public void innerBuild(List<TMenu> treeNodes, TMenu parentNode) {
//        Iterator<TMenu> var4 = treeNodes.iterator();
//        while (var4.hasNext()) {
//            TMenu childNode = var4.next();
//            if (parentNode.getId().equals(childNode.getPid())) {
//                List<TMenu> children = parentNode.getMenus();
//                if (children == null) {
//                    children = new ArrayList();
//                    parentNode.setMenus(children);
//                }
//                children.add(childNode);
//                innerBuild(treeNodes, childNode);
//            }
//        }
//    }

    @Override
    public List<Tree<String>> threeByUser(String userId){
        List<TMenu> menus = this.baseMapper.findByUserId(userId);
        List<Tree<String>> trees = CoverToTree(menus);
        return trees;
    }

    @Override
    public List<Tree<String>> allMneu() {
        LambdaQueryWrapper<TMenu> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.orderByAsc(TMenu::getSort);
        List<TMenu> menus = list(queryWrapper);
        List<Tree<String>> trees = CoverToTree(menus);
        return trees;
    }

    @Override
    public void saveOrUpdateMenu(MenuAddDto dto) {
        TMenu menu = new TMenu();
        BeanUtils.copyProperties(dto,menu);
        if(StringUtils.isBlank(dto.getId())){
            menu.setCreateTime(LocalDateTime.now());
        }else{
            menu.setUpdateTime(LocalDateTime.now());
        }
        saveOrUpdate(menu);
    }

    @Override
    public void delMenu(String id) {
        TMenu menu = getById(id);
        Assert.notNull(menu,"找不到该记录");
        if(Objects.equals(menu.getParentId(),"0")){// 父级菜单，删除其下级
            QueryWrapper<TMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TMenu::getParentId,menu.getId());
            List<TMenu> childs = list(queryWrapper);
            childs.stream().forEach(child -> delMenuRoleByMenuId(child.getId()));
        }
        // 删除菜单角色关系
        delMenuRoleByMenuId(id);
        // 删除菜单
        removeById(id);
    }


    /**
     * 删除菜单角色关系
     */
    public void delMenuRoleByMenuId(String menuId){
        QueryWrapper<TRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TRoleMenu::getMenuId,menuId);
        tRoleMenuMapper.delete(queryWrapper);
    }

    /**
     *
     * 将菜单数据统一转为tree的格式返回
     */
    private List<Tree<String>> CoverToTree(List<TMenu> menus) {
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setWeightKey("sort");
        // 转换器
        List<Tree<String>> list = TreeUtil.build(menus, "0", treeNodeConfig, (menu, tree) -> {
            tree.setId(menu.getId());
            tree.setParentId(menu.getParentId());
            tree.setWeight(menu.getSort());
            tree.setName(menu.getName());
            tree.putExtra("label",menu.getName());
            tree.putExtra("path",menu.getPath());
            tree.putExtra("icon",menu.getIcon());
            tree.putExtra("url",menu.getUrl());
        });
        return list;
    }


}
